package repository

import (
	"fitness/go-admin/internal/model"

	"gorm.io/gorm"
)

// EmojiRepository 表情数据访问层
type EmojiRepository struct {
	db *gorm.DB
}

// NewEmojiRepository 创建表情仓库
func NewEmojiRepository(db *gorm.DB) *EmojiRepository {
	return &EmojiRepository{db: db}
}

// ==================== 表情分类 ====================

// CreateCategory 创建表情分类
func (r *EmojiRepository) CreateCategory(category *model.EmojiCategory) error {
	return r.db.Create(category).Error
}

// GetCategoryByID 根据ID获取表情分类
func (r *EmojiRepository) GetCategoryByID(id uint) (*model.EmojiCategory, error) {
	var category model.EmojiCategory
	err := r.db.First(&category, id).Error
	if err != nil {
		return nil, err
	}
	return &category, nil
}

// GetCategoryList 获取表情分类列表
func (r *EmojiRepository) GetCategoryList(req *model.EmojiCategoryListReq) ([]model.EmojiCategory, int64, error) {
	var categories []model.EmojiCategory
	var total int64

	query := r.db.Model(&model.EmojiCategory{})

	// 启用状态筛选
	if req.IsEnabled != nil {
		query = query.Where("is_enabled = ?", *req.IsEnabled)
	}

	// 计数
	query.Count(&total)

	// 分页
	offset := (req.Page - 1) * req.PageSize
	err := query.Order("sort_order DESC, id ASC").
		Offset(offset).
		Limit(req.PageSize).
		Find(&categories).Error

	return categories, total, err
}

// UpdateCategory 更新表情分类
func (r *EmojiRepository) UpdateCategory(id uint, updates map[string]interface{}) error {
	return r.db.Model(&model.EmojiCategory{}).
		Where("id = ?", id).
		Updates(updates).Error
}

// DeleteCategory 删除表情分类
func (r *EmojiRepository) DeleteCategory(id uint) error {
	return r.db.Delete(&model.EmojiCategory{}, id).Error
}

// GetAllEnabledCategories 获取所有启用的分类
func (r *EmojiRepository) GetAllEnabledCategories() ([]model.EmojiCategory, error) {
	var categories []model.EmojiCategory
	err := r.db.Where("is_enabled = ?", true).
		Order("sort_order DESC, id ASC").
		Find(&categories).Error
	return categories, err
}

// ==================== 表情 ====================

// CreateEmoji 创建表情
func (r *EmojiRepository) CreateEmoji(emoji *model.Emoji) error {
	return r.db.Create(emoji).Error
}

// GetEmojiByID 根据ID获取表情
func (r *EmojiRepository) GetEmojiByID(id uint) (*model.Emoji, error) {
	var emoji model.Emoji
	err := r.db.Preload("Category").First(&emoji, id).Error
	if err != nil {
		return nil, err
	}
	return &emoji, nil
}

// GetEmojiByCode 根据代码获取表情
func (r *EmojiRepository) GetEmojiByCode(code string) (*model.Emoji, error) {
	var emoji model.Emoji
	err := r.db.Where("code = ?", code).First(&emoji).Error
	if err != nil {
		return nil, err
	}
	return &emoji, nil
}

// GetEmojiList 获取表情列表
func (r *EmojiRepository) GetEmojiList(req *model.EmojiListReq) ([]model.EmojiWithCategory, int64, error) {
	var emojis []model.EmojiWithCategory
	var total int64

	query := r.db.Model(&model.Emoji{}).
		Select("emojis.*, emoji_categories.name as category_name").
		Joins("LEFT JOIN emoji_categories ON emojis.category_id = emoji_categories.id")

	// 分类筛选
	if req.CategoryID != nil {
		query = query.Where("emojis.category_id = ?", *req.CategoryID)
	}

	// 类型筛选
	if req.Type != "" {
		query = query.Where("emojis.type = ?", req.Type)
	}

	// 启用状态筛选
	if req.IsEnabled != nil {
		query = query.Where("emojis.is_enabled = ?", *req.IsEnabled)
	}

	// 关键词搜索
	if req.Keyword != "" {
		query = query.Where("emojis.name LIKE ? OR emojis.code LIKE ?",
			"%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}

	// 计数
	query.Count(&total)

	// 分页
	offset := (req.Page - 1) * req.PageSize
	err := query.Order("emojis.category_id ASC, emojis.sort_order DESC, emojis.id ASC").
		Offset(offset).
		Limit(req.PageSize).
		Find(&emojis).Error

	return emojis, total, err
}

// UpdateEmoji 更新表情
func (r *EmojiRepository) UpdateEmoji(id uint, updates map[string]interface{}) error {
	return r.db.Model(&model.Emoji{}).
		Where("id = ?", id).
		Updates(updates).Error
}

// DeleteEmoji 删除表情
func (r *EmojiRepository) DeleteEmoji(id uint) error {
	return r.db.Delete(&model.Emoji{}, id).Error
}

// GetEmojisByCategoryID 根据分类ID获取表情列表
func (r *EmojiRepository) GetEmojisByCategoryID(categoryID uint) ([]model.Emoji, error) {
	var emojis []model.Emoji
	err := r.db.Where("category_id = ? AND is_enabled = ?", categoryID, true).
		Order("sort_order DESC, id ASC").
		Find(&emojis).Error
	return emojis, err
}

// GetAllEmojisByCategoriesWithEmojis 获取所有启用的分类及其表情
func (r *EmojiRepository) GetAllEmojisByCategoriesWithEmojis() ([]model.EmojiCategoryWithEmojis, error) {
	// 获取所有启用的分类
	var categories []model.EmojiCategory
	err := r.db.Where("is_enabled = ?", true).
		Order("sort_order DESC, id ASC").
		Find(&categories).Error
	if err != nil {
		return nil, err
	}

	// 获取所有启用的表情
	var emojis []model.Emoji
	err = r.db.Where("is_enabled = ?", true).
		Order("category_id ASC, sort_order DESC, id ASC").
		Find(&emojis).Error
	if err != nil {
		return nil, err
	}

	// 组织数据
	result := make([]model.EmojiCategoryWithEmojis, 0)
	for _, category := range categories {
		categoryWithEmojis := model.EmojiCategoryWithEmojis{
			ID:          category.ID,
			Name:        category.Name,
			Icon:        category.Icon,
			SortOrder:   category.SortOrder,
			Description: category.Description,
			Emojis:      []model.EmojiSimple{},
		}

		// 添加该分类下的表情
		for _, emoji := range emojis {
			if emoji.CategoryID == category.ID {
				categoryWithEmojis.Emojis = append(categoryWithEmojis.Emojis, model.EmojiSimple{
					ID:        emoji.ID,
					Name:      emoji.Name,
					Code:      emoji.Code,
					ImageURL:  emoji.ImageURL,
					Emoji:     emoji.Emoji,
					Type:      emoji.Type,
					SortOrder: emoji.SortOrder,
				})
			}
		}

		result = append(result, categoryWithEmojis)
	}

	return result, nil
}

// CheckCodeExists 检查表情代码是否存在
func (r *EmojiRepository) CheckCodeExists(code string) (bool, error) {
	var count int64
	err := r.db.Model(&model.Emoji{}).Where("code = ?", code).Count(&count).Error
	return count > 0, err
}

// IncrementUsageCount 增加表情使用次数
func (r *EmojiRepository) IncrementUsageCount(emojiID uint) error {
	return r.db.Model(&model.Emoji{}).
		Where("id = ?", emojiID).
		UpdateColumn("usage_count", gorm.Expr("usage_count + ?", 1)).Error
}

// GetHotEmojis 获取热门表情（按使用次数排序）
func (r *EmojiRepository) GetHotEmojis(limit int) ([]model.Emoji, error) {
	var emojis []model.Emoji
	err := r.db.Where("is_enabled = ?", true).
		Order("usage_count DESC, id ASC").
		Limit(limit).
		Find(&emojis).Error
	return emojis, err
}

// CountEmojisByCategory 统计分类下的表情数量
func (r *EmojiRepository) CountEmojisByCategory(categoryID uint) (int64, error) {
	var count int64
	err := r.db.Model(&model.Emoji{}).
		Where("category_id = ?", categoryID).
		Count(&count).Error
	return count, err
}

